var express = require('express');
var router = express.Router();
const shsDB = require("../db/index.js");
//网页端
//面对面建群 全局变量 faceToFaceList
// 点击建群 按请求的人加入userlist
router.post('/create', jwtVerify, function(req, res, next) {
	OperationfaceToFaceTime(); //建群再判断

	let obj = {
		code: 200,
		message: "请检查网络设置",
		type: 5,
		status: true,
		data: {
			message: "", //业务消息
		}
	}
	const Item = Object.assign({}, req.body);
	Item.fromId = req.shsImUserInfo.fromId
	Item.fromName = req.shsImUserInfo.fromName
	
	if (Item.groupNumber === undefined || !Item.fromId || !Item.fromName || !Item.ItemId) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	Item.createTime = getdate();
	let isCreated = false;
	let createId = 0;
	let userlist = "";
	let Sql = "";


	if (faceToFaceList[Item.groupNumber] != undefined) {
		if (faceToFaceList[Item.groupNumber].ItemId === Item.ItemId && new Date().getTime() - faceToFaceList[
				Item.groupNumber].onlineTime.getTime() > faceToFaceFailureTime) {
			obj = Object.assign({}, {
				code: 200,
				type: 5,
				status: false, //群聊失效false,反之 true
				data: {
					groupNumber: Item.groupNumber, //失效群聊名称
					ItemId: Item.ItemId
				},
				message: "建群时间过长,请重新操作"
			})
			res.end(JSON.stringify(obj));
			return;
		}

	} else {
		obj = Object.assign({}, {
			code: 200,
			type: 5,
			status: false, //群聊失效false,反之 true
			data: {
				groupNumber: Item.groupNumber, //失效群聊名称
				ItemId: Item.ItemId
			},
			message: "群聊不存在,请重新操作"
		})
		res.end(JSON.stringify(obj));
		return;
	}

	

	//判断是否已经加入过该群聊  // 计算群创建时间 时效性  onlineList: faceToFaceList[Item.groupNumber].onlineTime
	//先查有无群 有在看用户是否在群内  是返回 不是则更新
	//查看群聊用户数 是否超出设定
	if (faceToFaceList[Item.groupNumber].ItemId === Item.ItemId) {
		if (faceToFaceList[Item.groupNumber].intoUserList.size >= MaximumNumberOfPeople && !faceToFaceList[Item.groupNumber].intoUserList.has(Item.fromId)) {
			obj = Object.assign({}, {
				code: 200,
				type: 5,
				status: false, //群聊失效false,反之 true
				data: {
					groupNumber: Item.groupNumber, //失效群聊名称
					ItemId: Item.ItemId,
				},
				message: "该群聊已满，请重新操作",
			})
			res.end(JSON.stringify(obj));
			return;
		}else{
			faceToFaceList[Item.groupNumber].intoUserList.add(Item.fromId)
		}
	}
	Sql =
		`select Id,userlist,ItemId,createTime from shsgroup where groupname='${Item.groupNumber}' and signGroupNumber='' and status=1 and ItemId='${Item.ItemId}' ORDER BY createTime desc limit 0,1`;

	shsDB(Sql).then(data => {
		if (data.length === 0) {
			//创建群
			isCreated = true;
			let url = `${imageNowIP}/images/root/${Number.parseInt(Math.random()*6+1)}.webp`;
			let describe = Item.describe ? Item.describe : `"用户[${Item.fromId}]创建"`;
			Sql =
				`insert into shsgroup(Id,groupname,url,userlist,\`status\`,\`describe\`,ItemId,createTime,updateTime,isneed,signGroupNumber) values(null,'${Item.groupNumber}','${url}','${Item.fromId},',1,'${describe}','${Item.ItemId}','${Item.createTime}','${Item.createTime}',0,'')`

		} else {
			createId = data[0].Id;
			userlist = data[0].userlist + `${Item.fromId},`;
			Sql =
				`select Id,userlist,ItemId,createTime from shsgroup where groupname='${Item.groupNumber}' and signGroupNumber=''  and status=1 and userlist like "%${Item.fromId},%" and ItemId='${Item.ItemId}' ORDER BY createTime desc limit 0,1`;
		}
		return shsDB(Sql)
	}).then(data => {
		if (isCreated) {
			createId = data.insertId
			Sql =
				`insert into grouplastmsg(Id,groupId,status,lastMessage,createTime,updateTime) values(null,${createId},1,'${Item.fromName}加入群聊','${Item.createTime}','${Item.createTime}')`;
			return shsDB(Sql);
		} else {
			if (data.length === 0) {
				Sql = `update shsgroup set userlist='${userlist}' where Id=${createId} `;
				return shsDB(Sql);
			} else {
				throw new Error('join success');
			}
		}

	}).then(data => {
		if (isCreated) {
			throw new Error('join success');
		} else {
			Sql =
				`update grouplastmsg set lastMessage='${Item.fromName}加入群聊',updateTime='${Item.createTime}' where groupId=${createId} and status=1`
			return shsDB(Sql);
		}
	}).then(data => {
		if (!isCreated) {
			throw new Error('join success');
		}
		obj.message = "加入成功";

		res.end(JSON.stringify(obj));
		// 刷新联系人列表
		let send = {
			type: 9,
			code: 200,
			desc: "刷新联系人列表"
		}
		if (wsClients[Item.fromId] !== undefined) {
			wsClients[Item.fromId].forEach((client) => {
				if (client.wtoken != req.shsImUserInfo.token) {
					client.send(JSON.stringify(send));
				}
			});
		}
	}).catch(err => {
		if (err.message === "join success") {
			obj.message = "加入成功";

			res.end(JSON.stringify(obj));
			// 刷新联系人列表
			let send = {
				type: 9,
				code: 200,
				desc: "刷新联系人列表"
			}
			if (wsClients[Item.fromId] !== undefined) {
				wsClients[Item.fromId].forEach((client) => {
					if (client.wtoken != req.shsImUserInfo.token) {
						client.send(JSON.stringify(send));
					}
				});
			}
		} else {
			console.log(err);
			obj.code = 201;
			res.end(JSON.stringify(err));
		}

	})



});



module.exports = router;